import fs from 'fs/promises'

// 延迟
export const sleep = (time = 1000) => {
  return new Promise(resolve => {
    setTimeout(resolve, time)
  })
}

// 随机数
export const random = (min, max) => {
  return Math.floor(Math.random() * (max - min + 1) + min)
}

// 重试
export async function retry(fn, max = 5, time = 1000) {
  let index = 0

  while (index < max) {
    try {
      // 尝试执行操作
      const result = await fn()
      return result // 操作成功，返回结果
    } catch (error) {
      // console.error('retry error', error)
      console.error(`[retry] ${index + 1} failed: ${error?.message || error}`)
      index++

      if (index < max) await sleep(time)
      else {
        throw new Error(error)
      }
    }
  }
}

// 读取JSON
export async function readJson(path) {
  const text = await fs.readFile(path, 'utf-8')
  return JSON.parse(text)
}

// 保存JSON
export function saveJson(path, data) {
  return fs.writeFile(path, JSON.stringify(data, null, 2), 'utf-8')
}

// 队列
export async function queue(tasks, fn, options = {}) {
  const { limit, onStage } = {
    limit: 5,
    onStage: async () => {},
    ...options,
  }
  let queue = []

  for (let i = 0; i < tasks.length; i++) {
    const task = tasks[i]
    queue.push({
      task,
      index: i,
    })

    if (queue.length === limit || i === tasks.length - 1) {
      await Promise.all(queue.map(item => fn(item.task, item.index)))
      await onStage(i)
      queue = []
    }
  }
}
